package com.mls.guardian.appst.chain.excutor.Upgrade;

import com.mls.guardian.appst.chain.TaskExecutor;
import com.mls.guardian.appst.chain.TaskInvoker;
import com.mls.guardian.appst.chain.TaskResult;
import com.mls.guardian.appst.shell.ShellScriptExecutorFuture;
import com.mls.guardian.common.FileUtil;
import com.mls.guardian.config.VersionConfig;
import com.mls.guardian.dataobj.ModuleMessage;
import com.mls.guardian.em.ContainerRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Calendar;

/**
 * Created by root on 15-12-7.
 */
public class RestartExcutor implements TaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(RestartExcutor.class);

    @Override
    public TaskResult exec(TaskInvoker invoker) {
        String bashFilePath = System.getProperty("user.home") + File.separator + "guardianConfig" + File.separator + "guardian_" + System.currentTimeMillis() + ".sh";
        String gitAddress = invoker.getConfig().getGitAddress();
        String sourceDest = invoker.getConfig().getSourceDest();

        TaskResult result = null;
        try {
            log.info("----开始restart Guardian----");

            String timerPath = Paths.get(Paths.get(sourceDest).getParent().toString(), "app", "bin").toString();
            String timerFile = Paths.get(timerPath, "timer.sh").toString();

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, 1);//延迟一分钟

            int month = calendar.get(Calendar.MONTH) + 1;//[0-11]
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);

            String masterBash = minute + " " + hour + " " + day + " " + month + " * export LANG=zh_CN.UTF-8;/bin/sh " + timerPath + "/runserver.sh com.mls.guardian.MasterStartup MASTER > " + timerPath + "/nohup.out &";
            String slaveBash = minute + " " + hour + " " + day + " " + month + " * export LANG=zh_CN.UTF-8;/bin/sh " + timerPath + "/runserver.sh com.mls.guardian.MasterStartup SLAVE > " + timerPath + "/nohup.out &";

            FileUtil.append(bashFilePath, "cd " + timerPath);
            if (invoker.getRole().toString().equals(ContainerRole.MASTER.toString())) {
                FileUtil.write(timerFile, masterBash);

                FileUtil.append(bashFilePath, "pid=$(ps -ef|grep java |grep MASTER |awk '{print $2}')");
                FileUtil.append(bashFilePath, "echo killing $pid");
                FileUtil.append(bashFilePath, "OLD_IFS=\"$IFS\"");
                FileUtil.append(bashFilePath, "IFS=\" \"");
                FileUtil.append(bashFilePath, "arr=($pid)");
                FileUtil.append(bashFilePath, "IFS=\"$OLD_IFS\"");
                FileUtil.append(bashFilePath, "for s in ${arr[@]}");
                FileUtil.append(bashFilePath, "do");
                FileUtil.append(bashFilePath, "echo killed $s");
                FileUtil.append(bashFilePath, "kill -9 $s");
                FileUtil.append(bashFilePath, "done");
                FileUtil.append(bashFilePath, "echo kill pid finished");

                FileUtil.append(bashFilePath, "crontab -u root timer.sh");
            } else {
                FileUtil.write(timerFile, slaveBash);

                FileUtil.append(bashFilePath, "pid=$(ps -ef|grep java |grep SLAVE |awk '{print $2}')");
                FileUtil.append(bashFilePath, "echo killing $pid");
                FileUtil.append(bashFilePath, "OLD_IFS=\"$IFS\"");
                FileUtil.append(bashFilePath, "IFS=\" \"");
                FileUtil.append(bashFilePath, "arr=($pid)");
                FileUtil.append(bashFilePath, "IFS=\"$OLD_IFS\"");
                FileUtil.append(bashFilePath, "for s in ${arr[@]}");
                FileUtil.append(bashFilePath, "do");
                FileUtil.append(bashFilePath, "echo killed $s");
                FileUtil.append(bashFilePath, "kill -9 $s");
                FileUtil.append(bashFilePath, "done");
                FileUtil.append(bashFilePath, "echo kill pid finished");

                FileUtil.append(bashFilePath, "crontab -u root timer.sh");
            }
            FileUtil.append(bashFilePath, "sleep 1");
            FileUtil.append(bashFilePath, "echo done");

            //在这里记录版本号
            VersionConfig.write("upgradeVersion", invoker.getVersionTag());
            result = new ShellScriptExecutorFuture("sh " + bashFilePath).execute();

            //暂停一下
            int sleepSecond = invoker.getConfig().getRestartSleep();
            if (sleepSecond <= 0) {
                sleepSecond = 10;
            }
            try {
                Thread.sleep(sleepSecond * 1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        } catch (Exception e) {
            result = new TaskResult();
            result.setSuc(false);
            result.setError(e.getMessage());

            e.printStackTrace();
        } finally {
            try {
                Files.delete(Paths.get(bashFilePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("----结束restart Guardian[{}]----", result.isSuc());
        }


        if (result.isSuc() == true) {
            return invoker.invoke();
        }

        return result;
    }
}
